<?php

/**
 * Description of QuoteController
 *
 * @author NE
 */
class Backend_QuoteController extends RCMS_Core_BaseController {

	/**
	 * Data from shopping card config
	 * 
	 * @var array Name value pairs
	 */
	private $_shoppingConfig = array();

	/**
	 * Data from system config
	 *
	 * @var array Name value pairs
	 */
	private $_systemConfig = array();

	/**
	 * Initialization of the controller
	 * 
	 */
	public function init() {
        parent::init();
        $this->_checkLogin(array('preview', 'pdf'));
        $this->_model = new Default_Model_QuoteModel();
        $this->_shoppingConfig = $this->_model->selectShoppingConfig();
    }

	/**
	 * Index action.
	 *
	 * Shows quote existing and new quotes list
	 */
	public function indexAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		
		//assigning variables
		//quote statuses
		$this->view->quotesAvstatuses = array(
			'new'  => 'New',
			'sent' => 'Sent',
			'sold' => 'Sold',
			'lost' => 'Lost'
		);
		//information about all quotes
		$this->view->quotesData = $this->_getAllQuotes();
		$this->view->websiteUrl = $this->getWebsiteUrl();
		
		//for translator
		echo $this->_translator->processScreen($this->view->render($this->getViewScript()));
	}

	/**
	 * Edit action.
	 *
	 */
	public function editAction()
    {
        $this->_helper->viewRenderer->setNoRender(true);
        
		$quoteId = (int) $this->getRequest()->getParam('qid');
		if($quoteId > 0) {
			$generator = new RCMS_Object_Generator_Generator();
			$quote = new RCMS_Object_Quote_Quote($quoteId);
			$userCart = new RCMS_Object_Shopping_ShoppingUserCart($quote->getShoppingCartId());
			$cartData = $userCart->getCartData();
            //counting total price of all items in the user's cart
			$totalPrice = 0;
			foreach($cartData as $key => $value) {
				$totalPrice += $value['price'] * $value['count'];
			}
            //taxes counting
            $totalTax = $this->_countTaxes($userCart);
			//assigning varriables
			$this->view->quoteDetails = array(
				'quoteId'         => $quote->getId(),
				
				'hasPreview'      => ($quote->getContent() != ''),
				'quoteName'       => $quote->getName(),
				'quoteDate'       => date("Y-m-d", strtotime($quote->getDate())),
				'quoteIntMsg'     => $quote->getInternalMessage(),
				'quoteDisclaimer' => $quote->getDisclaimer(),
                'quoteShipping'   => false //$quote->getShipping()
			);
            if (!empty($this->_session->quotemailtext))
                $this->view->quoteDetails['mailToUser'] =  $this->_session->quotemailtext;
            else
                $this->view->quoteDetails['mailToUser'] = $this->_shoppingConfig['quote_email_body'];

            //shipping if it's enabled in config
            if ($this->_shoppingConfig['shipping_type'] != 'pickup'){
                $shipping = new RCMS_Object_Shipping_Shipping($quote->getShoppingCartId());
                $this->view->shippingData = $shipping->getShippingAddress();
                $this->view->quoteDetails['quoteShipping'] = $shipping->getShippingCost();
            }

			//all items in user's cart
			$this->view->totalPrice      = $totalPrice;
            $this->view->totalTax        = $totalTax;
			$this->view->cartData        = $cartData;
			$this->view->shoppingConfig  = $this->_shoppingConfig;
			$this->view->cartId          = $userCart->getId();
			$this->view->userMail        = $userCart->getEmail();
			$this->view->quoteEdit       = true;
            
			$this->view->additionalUserData = array(
                'name'     => $userCart->getName(),
				'address1' => $userCart->getAddress1(),
				'address2' => $userCart->getAddress2(),
                'company'  => $userCart->getCompany(),
				'country'  => $userCart->getCountry(),
				'state'    => $userCart->getState(),
				'city'     => $userCart->getCity(),
				'zip'      => $userCart->getZip(),
				'phone'    => $userCart->getPhone()
			);
		}
		$this->view->websiteUrl = $this->getWebsiteUrl();
		$this->view->path = $this->_config->website->website->path;
		//for translator
		echo $this->_translator->processScreen($this->view->render($this->getViewScript()));
	}


	public function addnewAction()
    {
		$userCart = new RCMS_Object_Shopping_ShoppingUserCart();
		$timePostfix = date('Ymd-His');
		$userCart->setName(RCMS_Object_QuickConfig_QuickConfig::$temporaryNewQuoteName . $timePostfix);
		$userCart->setEmail('email@email.com');
		$cartId = $userCart->save();
        
		$quote = new RCMS_Object_Quote_Quote();
		$quote->setShoppingCartId($cartId);
		$quote->setName($userCart->getName());
		$quote->setStatus(RCMS_Object_Quote_Quote::Q_STATUS_NEW);
		$quoteId = $quote->save();
        
        if ($quoteId > 0) {
            $this->_redirect($this->getWebSiteUrl() . 'sys/backend_quote/edit/qid/' . $quoteId);
        } else {
            $this->_redirect($this->getWebSiteUrl());
        }
	}

	public function updatequoteoncreationAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

        if($this->getRequest()->isPost()) {
			$quoteId = (int) $this->getRequest()->getParam('qid');
            
			$name = $this->getRequest()->getParam('name');
			$quoteMail = $this->getRequest()->getParam('qMail');
			$quoteDate = $this->getRequest()->getParam('qDate');
			
			$quote = new RCMS_Object_Quote_Quote($quoteId);
			$quote->setDate(date('Y-m-d H:i:s', strtotime($quoteDate)));
            $quote->save();

			$cart = new RCMS_Object_Shopping_ShoppingUserCart($quote->getShoppingCartId());
			$cart->setName($name);
			$cart->setEmail($quoteMail);
            $cart->setCompany(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('company')));
			$cart->setCountry(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('country')));
			$cart->setState(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('state')));
			$cart->setCity(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('city')));
			$cart->setZip(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('zip')));
			$cart->setAddress1(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('address1')));
			$cart->setAddress2(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('address2')));
			$cart->setPhone(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('phone')));
			$cart->save();

            if ($this->_shoppingConfig['shipping_type'] != 'pickup'){
                $this->_updateShipping($cart);
            }
            echo json_encode(array('error' => 0, 'msg' => 'success'));
		}
	}

	/**
	 * Update quote status. (AJAX calling in quote.js)
	 * 
	 */
	public function updatestatusAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
        
		if ($this->getRequest()->isPost()) {
			$quoteId = intval($this->getRequest()->getParam('qid'));
			$status = $this->getRequest()->getParam('status');
			$quote = new RCMS_Object_Quote_Quote($quoteId);
			$quote->setStatus($status);
			$result = $quote->save();

			if ($result) {
				echo json_encode(array('error' => 0, 'msg' => 'success'));
			} else {
				echo json_encode(array('error' => 1, 'msg' => 'Can\'t update quote status. Something went wrong'));
			}
		}
	}

	/**
	 * Delete quote. (AJAX calling in quote.js)
	 *
	 */
	public function deletequoteAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if ($this->getRequest()->isPost()) {
			$quoteId = intval($this->getRequest()->getParam('qid'));
			$quote = new RCMS_Object_Quote_Quote($quoteId);
			$userCart = new RCMS_Object_Shopping_ShoppingUserCart($quote->getShoppingCartId());
            $shipping = new RCMS_Object_Shipping_Shipping($userCart->getId());

			if ($quote->delete()) {
				$result = $userCart->delete();
				if ($result) {
                    $shipping->delete();
					echo json_encode(array('error' => 0, 'msg' => 'success'));
				} else {
					echo json_encode(array('error' => 1, 'msg' => 'Unable to remove user cart. Something went wrong'));
				}
			} else {
				echo json_encode(array('error' => 1, 'msg' => 'Unable to remove quote. Something went wrong'));
			}
		}
	}

	/**
	 * Generate quote action (AJAX calling in quote.js)
	 *
	 * Generate quote content for user and sends him an email with link to his quote preview
	 * 
	 */
	public function generateAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
        
		$generator = new RCMS_Object_Generator_Generator();
		$this->_systemConfig = $this->_model->selectSystemConfig();
		
		$quoteId = $this->getRequest()->getParam('qid');
		$quote = new RCMS_Object_Quote_Quote($quoteId);

                $emailToUser = RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('emailSend'));
                    
                if ($emailToUser == 'true') {
                    //text to put in email to user
                    $userMailText = RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('usrMailText'));
                    //sending email to user
                    $mailSent = $this->_sendMailToUser($quote->getShoppingCartId(), $quoteId, $userMailText);

                    //if mail sent, then we will generate quote content and set quote status as "sent"
                    if($mailSent === true) {
                        $userCart = new RCMS_Object_Shopping_ShoppingUserCart($quote->getShoppingCartId());
                        $totalTax = $this->_countTaxes($userCart);
                        $quote->setDisclaimer(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('disclaimer')));
                        $quote->setContent($generator->generateQuoteContent($quote, $userCart, $totalTax));
                        $quote->setInternalMessage(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('intMessage')));
                        $quote->setStatus(RCMS_Object_Quote_Quote::Q_STATUS_SENT);
                        $quote->save();

                        //send response wich shows that everything went well
                        echo json_encode(array('error' => 0, 'msg' => 'success'));
                    } else {
                        //if mail not sent, send error response
                        echo json_encode(array('error' => 1, 'msg' => 'Can not send email. Quote was not generated'));
                    }
                } elseif ($emailToUser == 'false') {
                    $userCart = new RCMS_Object_Shopping_ShoppingUserCart($quote->getShoppingCartId());
                    $totalTax = $this->_countTaxes($userCart);
                    $quote->setDisclaimer(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('disclaimer')));
                    $quote->setContent($generator->generateQuoteContent($quote, $userCart, $totalTax));
                    $quote->setInternalMessage(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('intMessage')));
                    $quote->save();

                    echo json_encode(array('error' => 0, 'msg' => 'saved'));
                }
                
                if ($this->_shoppingConfig['shipping_type'] != 'pickup'){
                    $this->_updateShipping($userCart);
                }
                $this->_session->quotemailtext = trim($this->getRequest()->getParam('usrMailText'));
                
	}

	/**
	 * Show quote preview
	 */
	public function previewAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		$preQuoteInfo = explode('.', $this->getRequest()->getParam('qid'));

		if ($preQuoteInfo[0] != $preQuoteInfo[2]) {
			echo '<h1>Ooops! Wrong quote?</h1>';
			return;
		}
		$quoteId = $preQuoteInfo[0];
		$quote = new RCMS_Object_Quote_Quote($quoteId);
		echo $this->_translator->processScreen($quote->getContent());
	}

	public function addproducttocartAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		$cartId = intval($this->getRequest()->getParam('cid'));
		$productId = intval($this->getRequest()->getParam('pid'));

		$userCart = new RCMS_Object_Shopping_ShoppingUserCart($cartId);
		$cartData = $userCart->getCartData();
		
		if(array_key_exists($productId, $cartData)) {
			$cartData[$productId]['count']++;
		}
		else {
			$product = new RCMS_Object_Product_Product($productId);
			$cartData[$productId] = array(
				'count' => 1,
				'photo' => $product->getPhoto(),
				'name'  => $product->getName(),
				'price' => $product->getPrice(),
				'note'  => '',
                'id'    => $product->getId()
			);
		}
		$userCart->setCartData($cartData);
		$result = $userCart->save();
		if($result) {
			echo json_encode(array('error' => 0, 'msg' => 'success'));
		}
		else {
			echo json_encode(array('error' => 1, 'msg' => 'Can not add product. Something went wrong'));
		}
	}

	/**
	 * Update user cart
	 * 
	 */
	public function updatecartAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		$cartId = $this->getRequest()->getParam('qid');
		$userCart = new RCMS_Object_Shopping_ShoppingUserCart($cartId);
		$cartData = $userCart->getCartData();
		//item that should be removed
		$toRemove = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('toRemove')));
		//items wich price should be updated
		$toUpdatePrice = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('toUpdPrice')));
		//items wich note should be updated
		$notes = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('notes')));
		//items wich quantity should be updated
		$toUpdateQty = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('toUpdQty')));
        $quoteId = (int) $this->getRequest()->getParam('quoteId');
        $quote = new RCMS_Object_Quote_Quote($quoteId);
        if ($quote->getId() > 0) {
            $quote->setDisclaimer(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('disclaimer')));
            $quote->setInternalMessage(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('intMsgText')));
            $quote->save();

            if ($this->_shoppingConfig['shipping_type'] != 'pickup'){
                $this->_updateShipping($userCart);
            }
        }
		//remove items from user cart
		if(!empty ($toRemove)) {
			foreach ($toRemove as $remItem) {
				if(array_key_exists($remItem, $cartData)) {
					unset ($cartData[$remItem]);
				}
			}
		}
		//update items price
		if(!empty ($toUpdatePrice)) {
			foreach ($toUpdatePrice as $priceItem) {
				$priceItemExploded = explode(',', $priceItem);
				if(array_key_exists($priceItemExploded[0], $cartData)) {
					$cartData[$priceItemExploded[0]]['price'] = $priceItemExploded[1];
				}
			}
		}
		//udate items qty
		if(!empty($toUpdateQty)) {
			foreach($toUpdateQty as $qtyItem) {
				$qtyItemExploded = explode(',', $qtyItem);
				if(array_key_exists($qtyItemExploded[0], $cartData)) {
					if($qtyItemExploded[1] == 0) {
						unset ($cartData[$qtyItemExploded[0]]);
						continue;
					}
					if($cartData[$qtyItemExploded[0]]['count'] != $qtyItemExploded[1]) {
						$cartData[$qtyItemExploded[0]]['count'] = $qtyItemExploded[1];
					}
				}
			}
		}
		//update items notes
		if(!empty($notes)) {
			foreach($notes as $noteData) {
				$expNote = explode(',', $noteData);
				if(array_key_exists($expNote[0], $cartData)) {
					$cartData[$expNote[0]]['note'] = $expNote[1];
				}
			}
		}
		//saving cart
        $this->_session->quotemailtext = trim($this->getRequest()->getParam('mailUserText'));
        $userCart->setCartData($cartData);
		$userCart->save();
	}

	/**
	 * Getting data about quotes from database
	 * 
	 */
	private function _getAllQuotes() {
		$quotesData = $this->_model->selectAllQuotes();
		return $quotesData;
	}

	/**
	 * Sending mail to the user
	 *
	 */
	private function _sendMailToUser($shoppingCartId, $quoteId, $mailText) {
		$userCart = new RCMS_Object_Shopping_ShoppingUserCart($shoppingCartId);
		$mail = new RCMS_Object_Mailer_Mailer();
		if($this->_systemConfig['use_smtp']) {
			$mail->setSmtpConfig($this->_systemConfig['smtp_login'], $this->_systemConfig['smtp_password'], $this->_systemConfig['smtp_host']);
			$mail->setTransport(RCMS_Object_Mailer_Mailer::MAIL_TYPE_SMTP);
		}
		$mail->setFrom($this->_shoppingConfig['company']);
		$mail->setFromMail($this->_shoppingConfig['email']);
		$mail->setTo($userCart->getName());
		$mail->setToMail($userCart->getEmail());
		$mail->setSubject($this->_shoppingConfig['quote_email_subj']);
        $mailText = str_replace('{$name}', $userCart->getName(), $mailText);
        $mailText = str_replace('{$date}', date('Y-m-d'), $mailText);
        $mailText = str_replace('{$quote_url}', $this->getWebSiteUrl() . 'sys/backend_quote/preview/qid/' . $quoteId . '.' . md5($quoteId) . '.' . $quoteId, $mailText);
		$mail->setBody($mailText);
		return $mail->send();
	}

    public function pdfAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        $quoteId = (int) $this->getRequest()->getParam('id');
        $quote = new RCMS_Object_Quote_Quote($quoteId);
        if ($quote->getId() <= 0) {
            return;
        }
        $pdf = new Zend_Pdf();
        $pdfPage = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
        $font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);
        $padding = 30;
        $encoding = 'UTF-8';

        /*** left block ***/
        $shoppingConfig = $this->_shoppingConfig;
        $companyLogo = trim($this->_config->website->website->path.'public/'.$shoppingConfig['company_logo']);
        $companyName = trim($shoppingConfig['company']);        
        $companyAddress = trim($shoppingConfig['address']);
        if (trim($shoppingConfig['address'])  != '' && trim($shoppingConfig['address2'])) $companyAddress .= ', ';
        if (trim($shoppingConfig['address2']) != '') $companyAddress .= $shoppingConfig['address2'];
        $companyAddress2 = trim($shoppingConfig['city']);
        if ((trim($shoppingConfig['city'])!='') and (trim($shoppingConfig['state'])!='' or trim($shoppingConfig['zip'])!='')) $companyAddress2 .= ', ';
        $companyAddress2 .= trim($shoppingConfig['state']);
        if (trim($shoppingConfig['state'])!='') $companyAddress2 .= ' ';
        $companyAddress2 .= trim($shoppingConfig['zip']);
        $companyCountry = trim($shoppingConfig['country']);
        $companyPhone = trim($shoppingConfig['phone']);
        $companyEmail = trim($shoppingConfig['email']);
        $img = null;
        $imageInfo = getimagesize($companyLogo);

        switch ($imageInfo['mime']){
            case 'image/png':
                $img = new Zend_Pdf_Resource_Image_Png($companyLogo);
                break;
            case 'image/jpeg':
                $img = new Zend_Pdf_Resource_Image_Jpeg($companyLogo);
                break;
            case 'image/tiff':
                $img = new Zend_Pdf_Resource_Image_Tiff($companyLogo);
                break;
            default:
                break;
        }
        
        if (is_file($companyLogo) && preg_match('/\.(png|jpg|jpe|jpeg|tiff|tif)$/', basename($companyLogo)) && is_object($img)) {
            $logoWidth = $img->getPixelWidth() < 200 ? $img->getPixelWidth() : 200;
            $logoHeight = $img->getPixelHeight() < 150 ? $img->getPixelHeight() : 150;
            $pdfPage->drawImage($img, $padding, ($pdfPage->getHeight() - $padding) - $logoHeight, $logoWidth, $pdfPage->getHeight() - $padding);
            $Y_HeightLeft = ($pdfPage->getHeight() - $padding) - $logoHeight;
        } else {
            $Y_HeightLeft = $pdfPage->getHeight() - $padding;
        }

        if ($companyName !== '') {
            $Y_HeightLeft -= 20;
            $pdfPage->setFont($font, 16);
            $pdfPage->drawText($companyName, $padding, $Y_HeightLeft, $encoding);
        }
        $pdfPage->setFont($font, 14);

        if ($companyAddress !== '') {
            $Y_HeightLeft -= 20;            
            $pdfPage->drawText($companyAddress, $padding, $Y_HeightLeft, $encoding);
        }

        if ($companyAddress2 !== '') {
            $Y_HeightLeft -= 20;
            $pdfPage->drawText($companyAddress2, $padding, $Y_HeightLeft, $encoding);
        }
        
        if ($companyCountry !== '') {
            $Y_HeightLeft -= 20;
            $pdfPage->drawText($companyCountry, $padding, $Y_HeightLeft, $encoding);
        }

        if ($companyPhone !== '') {
            $Y_HeightLeft -= 20;
            $pdfPage->drawText($companyPhone, $padding, $Y_HeightLeft, $encoding);
        }
        
        if ($companyEmail !== '') {
            $Y_HeightLeft -= 20;
            $pdfPage->drawText($companyEmail, $padding, $Y_HeightLeft, $encoding);
        }
        /*** end left block ***/

        /*** right block ***/
        $Y_HeightRight = $pdfPage->getHeight() - 40;
        $X_WidthRight = $pdfPage->getWidth() - 200;
        $pdfPage->setFont($font, 13);

        if($quote->getDate()) {
            $pdfPage->drawText(date("Y-m-d",strtotime($quote->getDate())), $pdfPage->getWidth()-100, $Y_HeightRight, $encoding);
        }
        $shoppingCart = new RCMS_Object_Shopping_ShoppingUserCart($quote->getShoppingCartId());

        if ($shoppingCart->getName()) {
            $Y_HeightRight -= 20;
            $pdfPage->drawText((strlen($shoppingCart->getName()) < 20 ? ucfirst($shoppingCart->getName()) : substr($shoppingCart->getName(), 0, 18).'...'), $X_WidthRight, $Y_HeightRight, $encoding);
        }

        if ($shoppingCart->getCompany()) {
            $Y_HeightRight -= 20;
            $pdfPage->drawText($shoppingCart->getCompany(), $X_WidthRight, $Y_HeightRight, $encoding);
        }
        $userPostAddress  = $shoppingCart->getAddress1();
        if ($shoppingCart->getAddress1() && $shoppingCart->getAddress1()) $userPostAddress .= ', ';
        $userPostAddress .= $shoppingCart->getAddress2();
        if ($userPostAddress) {
            $Y_HeightRight -= 20;
            $pdfPage->drawText($userPostAddress, $X_WidthRight, $Y_HeightRight, $encoding);
        }

        $userPostAddress2  = $shoppingCart->getCity();
        if ($shoppingCart->getCity() && ($shoppingCart->getState() or $shoppingCart->getZip())) $userPostAddress2 .= ', ';
        $userPostAddress2 .= $shoppingCart->getState();
        if ($shoppingCart->getState() && $shoppingCart->getZip()) $userPostAddress2 .= ' ';
        $userPostAddress2 .= $shoppingCart->getZip();

        if ($userPostAddress2) {
            $Y_HeightRight -=20;
            $pdfPage->drawText($userPostAddress2, $X_WidthRight, $Y_HeightRight, $encoding);
        }

        if ($shoppingCart->getCountry()) {
            $Y_HeightRight -=20;
            $pdfPage->drawText($shoppingCart->getCountry(), $X_WidthRight, $Y_HeightRight, $encoding);
        }
        if ($shoppingCart->getEmail()) {
            $Y_HeightRight -=20;
            $pdfPage->drawText($shoppingCart->getEmail(), $X_WidthRight, $Y_HeightRight, $encoding);
        }

        if ($shoppingCart->getPhone()) {
            $Y_HeightRight -= 20;
            $pdfPage->drawText($shoppingCart->getPhone(), $X_WidthRight, $Y_HeightRight, $encoding);
        }
        
        /*** end right block ***/

        /*** center block ***/
        $currency = $shoppingConfig['currency'];
        $pdfPage->setFont($font, 16);
        $pdfPage->drawText('Quote # ' . $quoteId, $pdfPage->getWidth()/2.25, 600, $encoding);
        $Y_HeightCenter = 570;
        
        $pdfPage->setFillColor(Zend_Pdf_Color_Html::color('#eeeeee'));
        $pdfPage->drawRectangle(0, 590, $pdfPage->getWidth(), 560, Zend_Pdf_Page::SHAPE_DRAW_FILL);

        $pdfPage->setFont($font, 14);
        $pdfPage->setFillColor(Zend_Pdf_Color_Html::namedColor('black'));
        $x_Pos = array (
            'photo'   => 50,
            'product' => 125,
            'note'    => 300,
            'qty'     => 425,
            'price'   => 485
            );
        $pdfPage->drawText('Photo', $x_Pos['photo'], $Y_HeightCenter, $encoding);
        $pdfPage->drawText('Product', $x_Pos['product']+50, $Y_HeightCenter, $encoding);
        $pdfPage->drawText('Note', $x_Pos['note']+25, $Y_HeightCenter, $encoding);
        $pdfPage->drawText('Qty', $x_Pos['qty'], $Y_HeightCenter, $encoding);
        $pdfPage->drawText('Price ('.$currency.')',  $x_Pos['price'], $Y_HeightCenter, $encoding);

        $data = $shoppingCart->getCartData(true);
        $Y_HeightCenter -= 15;
        $pdfPage->setFont($font, 10);
        $pdfPage->setLineColor(Zend_Pdf_Color_Html::color('#eeeeee'));
        $pdfPage->setLineWidth(0.5);
        $totalPrice = 0;
        $totalTax   = $this->_countTaxes($shoppingCart);
        foreach ($data as $item) {
            $photo = trim($this->_config->website->website->path.'public/'.$item['photo']);
            $img = null;
            $imageInfo = getimagesize($photo);
            
            switch ($imageInfo['mime']){
                case 'image/png':
                    $img = new Zend_Pdf_Resource_Image_Png($photo);
                    break;
                case 'image/jpeg':
                    $img = new Zend_Pdf_Resource_Image_Jpeg($photo);
                    break;
                case 'image/tiff':
                    $img = new Zend_Pdf_Resource_Image_Tiff($photo);
                    break;
                default:
                    break;
            }

            if (is_file($photo) && preg_match('/\.(png|jpg|jpe|jpeg|tiff|tif)$/', basename($photo)) && is_object($img)) {
                $pdfPage->drawImage($img, $x_Pos['photo'], $Y_HeightCenter-50, 100, $Y_HeightCenter);
            } else {
                $pdfPage->drawText('No Image', $x_Pos['photo']-10, $Y_HeightCenter-50, $encoding);
            }

            if (strlen($item['name']) > 30 && strpos($item['name'], ' ') !== false ) {
                $nameTmp = explode(' ', $item['name']);
                $nameStr = '';
                $y_Tmp = $Y_HeightCenter - 12;
                foreach ($nameTmp as $value) {
                    $nameStr .= $value . ' ';
                    if (strlen($nameStr)>=30) {
                        $pdfPage->drawText($nameStr, $x_Pos['product'], $y_Tmp, $encoding);
                        $y_Tmp -= 12;
                        $nameStr = '';
                    }
                }
                if ($nameStr) $pdfPage->drawText($nameStr, $x_Pos['product'], $y_Tmp, $encoding);
            } else {
                $pdfPage->drawText($item['name'], $x_Pos['product'], $Y_HeightCenter-30, $encoding);
            }
            
            $pdfPage->setFont($font, 8);
            if (strlen($item['note']) > 25 && strpos($item['note'], ' ') !== false) {
                $noteTmp = explode(' ', $item['note']);
                $noteStr = '';
                $y_Tmp = $Y_HeightCenter - 12;
                foreach ($noteTmp as $value) {
                    $noteStr .= $value . ' ';
                    if (strlen($noteStr)>=20) {
                        $pdfPage->drawText($noteStr, $x_Pos['note'], $y_Tmp, $encoding);
                        $y_Tmp -= 12;
                        $noteStr = '';
                    }
                }
                if ($noteStr) $pdfPage->drawText($noteStr, $x_Pos['note'], $y_Tmp, $encoding);
            } else {
                $pdfPage->drawText(substr($item['note'], 0, 24), $x_Pos['note'], $Y_HeightCenter-30, $encoding);
            }
            $pdfPage->setFont($font, 10);
            $pdfPage->drawText($item['count'], $x_Pos['qty']+5, $Y_HeightCenter-30, $encoding);
            $pdfPage->drawText($item['price'].' '.$currency, $x_Pos[price], $Y_HeightCenter-30, $encoding);
            $pdfPage->drawLine(0, $Y_HeightCenter-60, $pdfPage->getWidth(), $Y_HeightCenter-60);
            $totalPrice += $item['price'] * $item['count'];
            
            if ($Y_HeightCenter - 90 < 0) {
                $pdf->pages[] = $pdfPage;
                $pdfPage = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
                $pdfPage->setFont($font, 12);
                $pdfPage->setLineColor(Zend_Pdf_Color_Html::color('#eeeeee'));
                $pdfPage->setLineWidth(0.5);
                $Y_HeightCenter = $pdfPage->getHeight()-15;
            } else {
                $Y_HeightCenter -= 70;
            }

        }
        if ($Y_HeightCenter - 90 < 0) {
                $pdf->pages[] = $pdfPage;
                $pdfPage = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
                $pdfPage->setFont($font, 12);
                $pdfPage->setLineColor(Zend_Pdf_Color_Html::color('#eeeeee'));
                $pdfPage->setLineWidth(0.5);
                $Y_HeightCenter = $pdfPage->getHeight()-15;
        }

        if ($quote->getDisclaimer()) {
            $y_Tmp = $Y_HeightCenter - 20;
            //$pdfPage->drawText('Disclaimer: ', $x_Pos['photo'], $y_Tmp+15, $encoding);
            if (strlen($quote->getDisclaimer()) > 60 && strpos($quote->getDisclaimer(), ' ') !== false) {
                
                $disclaimerTmp = explode(' ', $quote->getDisclaimer());
                $disclaimerStr = '';
                
                foreach ($disclaimerTmp as $value) {
                    $disclaimerStr .= $value . ' ';
                    if (strlen($disclaimerStr)>=60) {
                        $pdfPage->drawText($disclaimerStr, $x_Pos['photo'], $y_Tmp, $encoding);
                        $y_Tmp -= 16;
                        $disclaimerStr = '';
                    }
                }
                if ($disclaimerStr) $pdfPage->drawText($disclaimerStr, $x_Pos['photo'], $y_Tmp, $encoding);
            } else {
                $pdfPage->drawText(substr($quote->getDisclaimer(), 0, 60), $x_Pos['photo'], $y_Tmp, $encoding);
            }
            //$pdfPage->drawText($quote->getDisclaimer(), 50, $Y_HeightCenter-40, $encoding);
        }

        $pdfPage->setFont($font, 14);
        
        if ($totalPrice) {
            $Y_HeightCenter -= 20;
            $pdfPage->drawText('Sub-total: ', $pdfPage->getWidth()-220, $Y_HeightCenter, $encoding);
            $pdfPage->drawText($totalPrice.' ('.$shoppingConfig['currency'].')', $pdfPage->getWidth()-140, $Y_HeightCenter, $encoding);
        }
        if ($totalTax) {
            $Y_HeightCenter -= 20;
            $pdfPage->drawText('Tax: ', $pdfPage->getWidth()-220, $Y_HeightCenter, $encoding);
            $pdfPage->drawText($totalTax.' ('.$shoppingConfig['currency'].')', $pdfPage->getWidth()-140, $Y_HeightCenter, $encoding);
        }
        if ($this->_shoppingConfig['shipping_type'] != 'pickup') {
            $shippObj = new RCMS_Object_Shipping_Shipping($shoppingCart->getId());

            $shipping = number_format($shippObj->getShippingCost(),2,'.','');
            if ($shipping) {
                $Y_HeightCenter -= 20;
                $pdfPage->drawText('Shipping: ', $pdfPage->getWidth()-220, $Y_HeightCenter, $encoding);
                $pdfPage->drawText($shipping.' ('.$shoppingConfig['currency'].')', $pdfPage->getWidth()-140, $Y_HeightCenter, $encoding);
            }
        }
        $Y_HeightCenter -= 10;
        $pdfPage->setLineColor(Zend_Pdf_Color_Html::color('#7c7c7c'));
        $pdfPage->setLineWidth(1.25);
        $pdfPage->drawLine($pdfPage->getWidth()-230, $Y_HeightCenter, $pdfPage->getWidth()-10, $Y_HeightCenter);

        $grandTotal = $totalPrice + $totalTax + $shipping;

        $Y_HeightCenter -= 20;
        $pdfPage->drawText('Grand Total: ', $pdfPage->getWidth()-220, $Y_HeightCenter, $encoding);
        $pdfPage->drawText($grandTotal.' ('.$shoppingConfig['currency'].')', $pdfPage->getWidth()-140, $Y_HeightCenter, $encoding);

        /*** end center block ***/
        
        $pdf->pages[] = $pdfPage;
        $pdfString = $pdf->render();
        $this->getResponse()->setHeader('Content-Type', 'application/pdf');
        echo $pdfString;
    }
    
    /**
     * Internal function that updates shipping information
     * @param RCMS_Object_Shopping_ShoppingUserCart $userCart
     * @access private
     * @return void
     */
    private function _updateShipping(RCMS_Object_Shopping_ShoppingUserCart $userCart){
        $shipping = new RCMS_Object_Shipping_Shipping($userCart->getId());
        $shippingCost = $this->getRequest()->getParam('shipping');

        if ($this->getRequest()->getParam('shippingData') == '1'){
            $shippingData = array(
                'firstname' => $userCart->getName(),
                'lastname'  => '',
                'email'     => $userCart->getEmail(),
                'address1'  => $userCart->getAddress1(),
                'address2'  => $userCart->getAddress2(),
                'city'      => $userCart->getCity(),
                'state'     => $userCart->getState(),
                'zip'       => $userCart->getZip(),
                'country'   => $userCart->getCountry(),
                'phone'     => $userCart->getPhone()
            );
        }elseif ($this->getRequest()->getParam('shippingData') == '0'){
            return false;
        }else{
            $shippingData = (array)json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('shippingData')));
        }
        $shipping->setShippingAddress($shippingData);
        $shipping->setShippingService(array('type' => 'manual quote', 'price' => $shippingCost));
        $shipping->saveShipping();

    }

    /**
     * Internal function recalculates taxes for taxable products in the cart
     * @param RCMS_Object_Shopping_ShoppingUserCart $userCart
     * @return string in number format xxx.xx
     * @access private
     */
    private function _countTaxes(RCMS_Object_Shopping_ShoppingUserCart $userCart) {
        $cartData = $userCart->getCartData();
        $totalTax = 0;
        $taxRules = unserialize($this->_shoppingConfig['tax-rules']);

        $shipping = new RCMS_Object_Shipping_Shipping($userCart->getId());
        $shippingAddress = $shipping->getShippingAddress();
        unset($shipping);
        
        if (empty($shippingAddress) || $this->_shoppingConfig['shipping_type'] == 'pickup'){
            $shippingAddress = array (
                'country' => $userCart->getCountry(),
                'state' => $userCart->getState()
            );
        }

        foreach ($taxRules as $rule) {
            
            if (($rule['zone'] == $shippingAddress['country'] && $shippingAddress['state'] != '' && strpos($rule['subzone'],$shippingAddress['state'])!==false)
                || (($shippingAddress['state'] == '' || empty($shippingAddress['state'])) && strpos($rule['subzone'],$shippingAddress['country'])!==false) ){
                
                foreach ($cartData as $key => $value) {
                    $product = new RCMS_Object_Product_Product($value['id']);
                    if ($product->getId() > 0  && $product->getTax()) {
                        $totalTax += $value['count'] * $value['price'] * ($rule['tax'][$product->getTax()] / 100);
                    }
                    unset($product);
                }
            }
        }
        return number_format($totalTax,2,'.','');
    }
}